#region (c) 2014 THN Solutions LLC. - All rights reserved
/*
THN DATA ABSTRACTION LAYER version 1

Copyright (c) 2014, THN Solutions LLC. ( www.ThnSolutions.com )
Author: Nguyễn, M. Hải                 ( www.Minh-Hai.com     )
All rights reserved.

This library is dual-licensed.
  + For commercial software, please obtain a commercial license from THN Solutions LLC.

  + For free software, this library is licensed under GPL version 3. A summary of GPLv3 is
    listed below. You should also find a copy of GPLv3 as file License_GPLv3.txt included
	with the source-code files.

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License version 3 as published by
    the Free Software Foundation  of the License.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#endregion

#region Using directives
using System;
using System.Collections;
using Thn.Application;
#endregion

namespace Thn.Data.Persistence
{
    /// <summary>
    /// Provides in-memory cache service for persistent context
    /// </summary>
    public class PersistentCache : IPersistentCache
    {
        /// <summary>
        /// Cache of objects by types
        /// <para>key   : Type</para>
        /// <para>value : Hashtable containing objects of that particular type</para>
        /// </summary>
        Hashtable mObjectByTypes = new Hashtable();
        /// <summary>
        /// Hash of cache mode for different object types.
        /// <para>key   : Type</para>
        /// <para>value : CacheMode</para>
        /// </summary>
        Hashtable mCacheModes = new Hashtable();

        #region Get Object Cache
        /// <summary>
        /// Gets a hashtable containing objects of a particular type
        /// </summary>
        /// <param name="objectType">type of object to look for</param>
        protected Hashtable GetObjectCache(Type objectType)
        {
            Hashtable result = null;

            if (mObjectByTypes.Contains(objectType)) result = (Hashtable)mObjectByTypes[objectType];
            else
            {
                result = new Hashtable();
                mObjectByTypes.Add(objectType, result);
            }

            return result;
        }
        #endregion

        #region Can Cache
        /// <summary>
        /// Determine whether a particular persistent object is cachable.
        /// </summary>
        public virtual bool CanCache(IPersistentObject value)
        {
            bool result = false;
            Type valueType = value.GetType();

            if (mCacheModes.Contains(valueType))
            {
                CacheMode mode = (CacheMode)mCacheModes[valueType];
                result = mode == CacheMode.All;
            }
            else
            {
                object[] attributes = valueType.GetCustomAttributes(typeof(CachedAttribute), true);
                if ((attributes != null) && (attributes.Length > 0))
                {
                    CachedAttribute cachable = (CachedAttribute)attributes[0];
                    CacheMode mode = cachable.Mode;
                    result = mode == CacheMode.All;
                    
                    //store for next time
                    mCacheModes.Add(valueType, mode);
                }
            }

            return result;
        }
        #endregion

        #region Save
        /// <summary>
        /// Put an object to cache
        /// </summary>
        public void Save(IPersistentObject value)
        {
            if (CanCache(value))
            {
                Hashtable cache = GetObjectCache(value.GetType());
                object id = value.GetIdentifier();

                if (cache.Contains(id)) cache.Remove(id);
                cache.Add(id, value);
            }
        }
        #endregion

        #region Find
        /// <summary>
        /// Find an object from cache, given the object's identifier
        /// </summary>
        /// <param name="objectType">type of object to look for</param>
        /// <param name="id">identifier of the object</param>
        /// <returns>Null if none matches</returns>
        public IPersistentObject Find(Type objectType, object id)
        {
            IPersistentObject result = null;
            Hashtable cache = GetObjectCache(objectType);

            if (cache.Contains(id)) result = (IPersistentObject)cache[id];

            return result;
        }
        #endregion

        #region Remove
        /// <summary>
        /// Remove a particular object from cache
        /// </summary>
        public void Remove(IPersistentObject value)
        {
            Hashtable cache = GetObjectCache(value.GetType());
            object id = value.GetIdentifier();
            if (cache.Contains(id)) cache.Remove(id);
        }
        #endregion

        #region Clear
        /// <summary>
        /// Remove all objects from cache
        /// </summary>
        public void Clear()
        {
            mObjectByTypes.Clear();
            mCacheModes.Clear();
        }
        
        /// <summary>
        /// Removes certain type of objects from cache
        /// </summary>
        public void Clear(Type objectType)
        {
            Hashtable cache = GetObjectCache(objectType);
            cache.Clear();            
        }
        #endregion

        #region Log Contents
        /// <summary>
        /// This method is for debugging purpose. Write the content of this cache to log.
        /// </summary>
        public void Debug_LogContents()
        {
            ICollection keys = mObjectByTypes.Keys;
            object scope = Log.Start("Persistent Cache");
            foreach (Type valueType in keys)
            {
                object typeScope = Log.Start(valueType.Name);

                Hashtable cache = (Hashtable)mObjectByTypes[valueType];
                ICollection objects = cache.Values;

                foreach (object obj in objects)
                {
                    if (obj is IPersistentObject)
                    {
                        IPersistentObject po = (IPersistentObject)obj;
                        object id = po.GetIdentifier();
                        Log.Debug(string.Format("ID: {0} - Modified: {1} - Persistent: {2} - Object: {3}", id, po.Modified, po.Persistent, po));
                    }
                    else Log.Debug(string.Format("{0}", obj));
                }

                Log.End(typeScope);
            }
            Log.End(scope);
        }
        #endregion

        #region Constructors
        /// <summary>
        /// Default constructor
        /// </summary>
        public PersistentCache()
        { }
        #endregion
    }
}
